#include "connectevent.hpp"
#include "logger.hpp"

namespace oraysock5 {

ConnectEvent::ConnectEvent(std::shared_ptr<IPAddress> connect_addr,
    __socket_type type)
{
    connect_addr_ = connect_addr;
    type_ = type;
}

ConnectEvent::ConnectEvent(const char* hostname, short port,
    __socket_type type)
{
    hostname_ = hostname;
    dnsport_ = port;
    type_ = type;
    struct hostent* phe = gethostbyname(hostname);
    if (phe == nullptr || phe->h_addr_list[0] == nullptr) {
        THROW_EXCEPTION("call gethostbyname");
    }
    struct in_addr addr;
    memset(&addr, 0, sizeof(in_addr));
    memcpy(&addr, phe->h_addr_list[0], sizeof(struct in_addr));
    char ip[65] = { 0 };
    strcpy(ip, inet_ntoa(addr));
    connect_addr_ = std::make_shared<IPAddress>(ip, port);
}

ConnectEvent::~ConnectEvent()
{
    if (dnsbase_ != nullptr) {
        evdns_base_free(dnsbase_, 0);
    }
}

}
